from pydash import _
import dbm.dumb
import sys
import inquirer
import dbm
import shelve
import json
import subprocess
import datetime
from rocksdict import Rdict
from tencent_api import Solutions as TencentApiSolutions
import pandas as pd


from pathlib import Path

current_dir = Path(__file__).parent

ss = TencentApiSolutions()


class Solutions:
    def __init__(self):
        db = Rdict(f"{current_dir}/test.db")
        self.servers = db.get("servers", "[]")
        self.disks = db.get("disks", "[]")
        db.close()

    def refresh(self):
        servers = ss.get_all_server_simple()
        db = Rdict(f"{current_dir}/test.db")
        db["servers"] = servers
        db["servers_update_time"] = datetime.datetime.now().strftime(
            "%Y-%m-%d %H:%M:%S"
        )
        db.close()
        return servers

    def refresh_disk(self):
        disks = ss.get_all_disk_simple()
        db = Rdict(f"{current_dir}/test.db")
        db["disks"] = disks
        db["disks_update_time"] = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        db.close()
        return disks

    def print_all_servers(self):
        results = []
        for i in self.servers:
            results.append(
                f"{i['InstanceName']} {i['PublicIpAddresses']} {i['AccountName']}"
            )
        print("\n".join(results))

    def main(self):
        # print(self.servers)

        choices = [
            f"{index} {i['InstanceName']}_{i['PublicIpAddresses']}"
            for index, i in enumerate(self.servers)
        ]

        questions = [
            inquirer.List("server", message="What size do you need?", choices=choices),
        ]

        answers = inquirer.prompt(questions)
        print(answers)
        index = int(answers["server"].split(" ")[0])
        server = self.servers[index]
        private_ip_address = server["PrivateIpAddresses"]

        sh_cmd = f"ssh -J ubuntu@106.52.94.25 ubuntu@{private_ip_address}"
        print(sh_cmd)
        subprocess.run(sh_cmd, shell=True)

    def search(self):
        input = inquirer.text("input")
        choices = [
            f"{index} {i['InstanceName']}_{i['PublicIpAddresses']}_{i['PrivateIpAddresses']}\t\t[{i['AccountName']}]"
            for index, i in enumerate(self.servers)
        ]
        choices = _.filter(choices, lambda x: input in x)
        questions = [
            inquirer.List("server", message="What size do you need?", choices=choices),
        ]
        answers = inquirer.prompt(questions)
        print(answers)
        index = int(answers["server"].split(" ")[0])
        server = self.servers[index]
        private_ip_address = server["PrivateIpAddresses"]

        sh_cmd = f"ssh -J ubuntu@106.52.94.25 ubuntu@{private_ip_address}"
        print(sh_cmd)
        subprocess.run(sh_cmd, shell=True)

    def cmd(self, search_text, ext_parameters):
        servers = (
            _(self.servers).filter(lambda x: search_text in x["InstanceName"]).value()
        )
        prefix = "ssh -J ubuntu@106.52.94.25 "
        cmds = [
            f"{prefix} ubuntu@{i['PrivateIpAddresses']} {ext_parameters}"
            for i in servers
        ]
        print("\n".join(cmds))

    def innet(self, search_text):
        servers = (
            _(self.servers).filter(lambda x: search_text in x["InstanceName"]).value()
        )
        cmds = [i["PrivateIpAddresses"] for i in servers]
        print("\n".join(cmds))

    def server_count_expired_in_days(self, days):
        df = pd.DataFrame(self.servers)
        return len(df[df["days_left"] < days])

    def server_expired_in_days(self, days):
        df = pd.DataFrame(self.servers)
        return df[df["days_left"] < days][
            [
                "InstanceName",
                "AccountName",
                "PrivateIpAddresses",
                "PublicIpAddresses",
                "CPU",
                "Memory",
                "days_left",
                "ExpiredTime",
            ]
        ]

    def disks_expired_in_days(self, days):
        df = pd.DataFrame(self.disks)
        return df[df["days_left"] < days][
            [
                "DiskName",
                "DiskUsage",
                "days_left",
                "ExpiredTime",
            ]
        ]


if __name__ == "__main__":
    # argslen > 1
    if len(sys.argv) > 1:
        if sys.argv[1] == "print":
            Solutions().print_all_servers()
        if sys.argv[1] == "refresh":
            Solutions().refresh()
        if sys.argv[1] == "search":
            Solutions().search()
        if sys.argv[1] == "cmd":
            Solutions().cmd(sys.argv[2])

    elif len(sys.argv) == 1:
        Solutions().search()
